package org.gpslw.supermap;


import org.apache.commons.collections4.CollectionUtils;
import org.geotools.api.feature.simple.SimpleFeatureType;
import org.geotools.api.feature.type.FeatureType;
import org.geotools.api.feature.type.Name;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.internal.WFSClient;
import org.geotools.data.wfs.internal.parsers.EmfAppSchemaParser;
import org.geotools.feature.NameImpl;

import javax.xml.namespace.QName;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

public class SuperMapWfsDataStore extends WFSDataStore {


    public SuperMapWfsDataStore(WFSClient client) {
        super(client);
    }

    @Override
    public QName getRemoteTypeName(Name localTypeName) throws IOException {
        QName qNa = super.getRemoteTypeName(localTypeName);
//        if (qNa.getNamespaceURI().startsWith("http://www.supermap.com") && !qNa.getNamespaceURI().startsWith("http://www.supermap.com.cn")){
//            qNa = new QName("http://www.supermap.com.cn", qNa.getLocalPart(), qNa.getPrefix());
//        }
        return qNa;
    }


    @Override
    protected List<Name> createTypeNames() throws IOException {
        List<Name> typeNames = super.createTypeNames();
//        if (CollectionUtils.isNotEmpty(typeNames)){
//            typeNames.forEach(name -> {
//                if (name.getNamespaceURI().startsWith("http://www.supermap.com") && !name.getNamespaceURI().startsWith("http://www.supermap.com.cn")){
//                    //nameSpace替换，使用反射
//                    try {
//                        Field namespaceField = ((NameImpl) name).getClass().getDeclaredField("namespace");
//                        namespaceField.setAccessible(true);
//                        namespaceField.set(name, name.getNamespaceURI().replace("http://www.supermap.com", "http://www.supermap.com.cn"));
//                    } catch (IllegalAccessException e) {
//                        throw new RuntimeException(e);
//                    } catch (NoSuchFieldException e) {
//                        throw new RuntimeException(e);
//                    }
//                }
//            });
//        }
        return typeNames;
    }

    public SimpleFeatureType getRemoteSimpleFeatureType(QName remoteTypeName) throws IOException {
//        if (remoteTypeName.getNamespaceURI().startsWith("http://www.supermap.com") && !remoteTypeName.getNamespaceURI().startsWith("http://www.supermap.com.cn")){
//            String newNamespaceURI = remoteTypeName.getNamespaceURI().replace("http://www.supermap.com", "http://www.supermap.com.cn");
//            remoteTypeName = new QName(newNamespaceURI, remoteTypeName.getLocalPart(), remoteTypeName.getPrefix());
//        }

        return super.getRemoteSimpleFeatureType(remoteTypeName);
    }


}
